<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="会员姓名" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入会员姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="会员电话" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="请输入会员电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="会员邮箱" prop="mail">
              <el-input v-model="queryParams.mail" placeholder="请输入会员邮箱" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="id" align="center" prop="id" />
        <el-table-column label="会员姓名" align="center" prop="name" />
        <el-table-column label="会员电话" align="center" prop="phone" />
        <el-table-column label="会员邮箱" align="center" prop="mail" />
        <el-table-column label="会员生日" align="center" prop="birthDay" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthDay, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="会员余额" align="center" prop="money" />
        <el-table-column label="会员状态：0挂失/1正常/2销户" align="center" prop="status">
          <template #default="scope">
            {{ statusMap[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="激活" placement="top">
              <el-button link type="success" icon="Unlock" @click="handleActive(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="重置密码" placement="top">
              <el-button link type="warning" icon="Refresh" @click="handleReset(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改顾客管理对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="customerFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="会员姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入会员姓名" />
        </el-form-item>
        <el-form-item v-if="showPhone" label="会员电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入会员电话" />
        </el-form-item>
        <el-form-item v-if="showPhone" label="会员密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入会员密码" />
        </el-form-item>
        <el-form-item label="会员邮箱" prop="mail">
          <el-input v-model="form.mail" placeholder="请输入会员邮箱" />
        </el-form-item>
        <el-form-item label="会员生日" prop="birthday">
          <el-date-picker v-model="form.birthDay" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择会员生日"> </el-date-picker>
        </el-form-item>
        <el-form-item label="会员余额" prop="money">
          <el-input v-model="form.money" placeholder="请输入会员余额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Customer" lang="ts">
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer, activeCustomer, resetPassword } from '@/api/billiards/customer';
import { CustomerVO, CustomerQuery, CustomerForm } from '@/api/billiards/customer/types';
import { parseTime } from '../../../utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const customerList = ref<CustomerVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const statusMap = ['挂失', '正常', '销户'];
const queryFormRef = ref<ElFormInstance>();
const customerFormRef = ref<ElFormInstance>();
let showPhone = false;
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: CustomerForm = {
  id: undefined,
  name: undefined,
  phone: undefined,
  password: undefined,
  mail: undefined,
  birthDay: undefined,
  money: undefined,
  status: undefined
};
const data = reactive<PageData<CustomerForm, CustomerQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    phone: undefined,
    password: undefined,
    mail: undefined,
    birthDay: undefined,
    money: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '会员姓名不能为空', trigger: 'blur' }],
    phone: [
      { required: true, message: '会员电话不能为空', trigger: 'blur' },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
    ],
    password: [
      { required: true, message: '会员密码不能为空', trigger: 'blur' },
      { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
      { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur' }
    ],
    mail: [
      { required: true, message: '会员邮箱不能为空', trigger: 'blur' },
      {
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: ['blur', 'change']
      }
    ],
    birthDay: [{ required: true, message: '会员生日不能为空', trigger: 'blur' }],
    money: [{ required: true, message: '会员余额不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '会员状态：0挂失/1正常/2销户不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询顾客管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCustomer(queryParams.value);
  customerList.value = res.data.rows;
  total.value = res.data.total;
  loading.value = false;
  console.log(customerList.value);
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  customerFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CustomerVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  showPhone = true;
  dialog.visible = true;
  dialog.title = '添加顾客管理';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CustomerVO) => {
  reset();
  showPhone = false;
  const _id = row?.id || ids.value[0];
  queryParams.value = { id: _id };
  const res = await listCustomer(queryParams.value);
  Object.assign(form.value, res.data.rows[0]);
  dialog.visible = true;
  dialog.title = '修改顾客管理';
};

/** 提交按钮 */
const submitForm = () => {
  customerFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateCustomer(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addCustomer(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: CustomerVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除顾客管理编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delCustomer(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleActive = async (row?: CustomerVO) => {
  const _phone = row?.phone || ids.value;
  await proxy?.$modal.confirm('是否确认激活"' + _phone + '“？').finally(() => (loading.value = false));
  await activeCustomer(_phone);
  proxy?.$modal.msgSuccess('激活成功');
  await getList();
};

const handleReset = async (row?: CustomerVO) => {
  await proxy?.$modal.confirm('是否重置"' + row.name + '“的登录密码？').finally(() => (loading.value = false));
  row.password = 'e10adc3949ba59abbe56e057f20f883e';
  var res = await resetPassword(row);
  proxy?.$modal.msgSuccess(res.msg);
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/customer/export',
    {
      ...queryParams.value
    },
    `customer_${new Date().getTime()}.xlsx`
  );
};

// const handleReset = (row?: CustomerVO) => {
//   await proxy?.$modal.confirm('是否确认激活' + row.name + '"的登录密码？').finally(() => (loading.value = false));
//   await activeCustomer(_phone);
//   proxy?.$modal.msgSuccess('激活成功');
//   await getList();
// };
onMounted(() => {
  getList();
});
</script>
